
from ConfigParser import ConfigParser
import os
from PyQt4.QtXml import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class EntityFactory(object):

	class Entity:
		def __init__(self, node, image=None):
			self.name = str(node.attribute("name"))
			self.image = image
			self.speed = int(node.attribute("speed"))
			self.hp = int(node.attribute("hp"))

	# singleton
	instance = None
	def __new__(klass):
		if klass.instance is None:
			klass.instance = object.__new__(klass)
			klass.instance.load()
		return klass.instance

	def load(self):
		self.images = {}
		self.mobs = {}
		self.decors = {}
		self.items = {}

		conf = ConfigParser()
		conf.read("config/config.ini")
		path = conf.get("path", "resources")

		# load animations
		try:
			content = open(path + "/xml/animations.xml").read()
			document = QDomDocument()
			success, error_msg, line, col = document.setContent(content)
			if not success:
				raise IOError("%s (line %d, column %d)" % (error_msg, line, col))
		except IOError as e:
			print e
		else:
			print "* load animations..."
			root = document.documentElement()
			node_anim = root.firstChildElement("animation")
			while not node_anim.isNull():
				anim_id = str(node_anim.attribute("id"))
				anim_image_filename = os.path.join(path, "images", str(node_anim.attribute("file")))

				anim_image = QPixmap(anim_image_filename)

				frames = node_anim.firstChildElement("frames")
				frame_width = int(frames.attribute("width"))
				frame_height = int(frames.attribute("height"))

				anim_image = anim_image.copy(0, 0, frame_width, frame_height)

				self.images[anim_id] = anim_image
				node_anim = node_anim.nextSiblingElement("animation")

		# load enities
		try:
			content = open(path + "/xml/entities.xml").read()
			document = QDomDocument()
			success, error_msg, line, col = document.setContent(content)
			if not success:
				raise IOError("%s (line %d, column %d)" % (error_msg, line, col))
		except IOError as e:
			print e
		else:
			print "* load entities..."
			root = document.documentElement()
			# parse mobs
			node_mob = root.firstChildElement("mobs").firstChildElement()
			while not node_mob.isNull():
				mob_id = str(node_mob.attribute("id"))
				self.mobs[mob_id] = self.Entity(node_mob, self.images[mob_id])
				node_mob = node_mob.nextSiblingElement()

	def get_mob(self, mob_id):
		return self.mobs[str(mob_id)]

	def get_decor(self, decor_id):
		return self.decors[decor_id]

	def get_item(self, item_id):
		return self.items[item_id]
